package com.hnas.ecard.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.hnas.common.util.CommonUtils;
import com.hnas.common.web.BaseAjaxResponse;
import com.hnas.core.dto.DTOPagedList;
import com.hnas.core.dto.DataBean;
import com.hnas.core.util.MD5Util;
import com.hnas.ecard.service.CommoditMrchService;
import com.hnas.ecard.service.CommoditService;
import com.hnas.ecard.service.dto.DTOCommodit;
import com.hnas.ecard.service.dto.DTOCommoditMrch;
import com.hnas.ecard.service.dto.DTOCommoditMrchSearch;
import com.hnas.ecard.service.search.DTOCommoditSearch;
import com.hnas.hnt.service.IMrchService;

@Controller
@RequestMapping("/backend/commodit")
public class CommoditController {
	
	private ObjectMapper objectMapper = new ObjectMapper();
	private Logger logger = LoggerFactory.getLogger(CommoditController.class);
	
	@Value("#{component['uploadFileSize']}")
	private String uploadFileSize;

	@Autowired
	private CommoditMrchService commoditMrchService;
	@Autowired
	private IMrchService mrchService;
	@Autowired
	private CommoditService commoditService;

	@RequestMapping("/mrch")
	public String searchMrch(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("criteria") DTOCommoditMrchSearch criteria) {
		//TODO
		criteria.setTotalCount(-1);
		DTOPagedList<DTOCommoditMrch> pg = this.commoditMrchService.page(criteria);
		modelMap.put("pg", pg);
		modelMap.put("dto", criteria);
		
		List<DataBean> beans = new ArrayList<DataBean>();
		beans.add(new DataBean("id", "id", "id", false, 150, 0));
		beans.get(beans.size() - 1).setHidden(true);
		beans.add(new DataBean("mrchId", "mrchId", "商户编号", false, 150, 0));
		beans.add(new DataBean("mrchName", "mrchName", "商户名称", false, 150, 0));
		beans.add(new DataBean("mrchPic", "mrchPic", "商户图片", false, 150, 0));
		beans.add(new DataBean("address", "address", "商户地址", false, 150, 0));
		beans.add(new DataBean("createTime", "createTime", "创建时间", false, 150, 0));
		modelMap.put("beans", beans);
		modelMap.put("pageTitle", "商品商户信息");
	
		return "backend/ecard/list_commodit_mrch";
	}
	
	@RequestMapping(value="/addCommoditMrch",method=RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse addCommoditMrch(HttpServletRequest request,DTOCommoditMrch dto) throws IOException {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			dto.setId(CommonUtils.getUUID());
			//根据商户号，查询商户名称
			String mrchName = this.mrchService.getMrchNameById(dto.getMrchId());
			dto.setMrchName(mrchName);
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				MultipartFile file = multiRequest.getFile("addMrchPicFile");
				if (null != file&&file.getSize()>0) {
					String filePath = request.getServletContext().getRealPath("/") + "upload";
					String mrchPic = "/upload"+ writeFile(file, filePath);
					dto.setMrchPic(mrchPic);
				}
			}
			this.commoditMrchService.saveOrUpdate(dto);
			res.setErrorMessage("添加商品商户成功");
			res.setResult(1);
		}catch(Exception e) {
			logger.error("添加商品商户异常：",e);
			res.setResult(2);
			res.setErrorMessage("添加商品商户失败");
		}
		return res;
	}
	
	@RequestMapping(value="/editCommoditMrch",method=RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse editCommoditMrch(HttpServletRequest request,DTOCommoditMrch dto) throws IOException {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			//根据商户号，查询商户名称
			String mrchName = this.mrchService.getMrchNameById(dto.getMrchId());
			dto.setMrchName(mrchName);
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				MultipartFile file = multiRequest.getFile("editMrchPicFile");
				if (null != file&&file.getSize()>0) {
					String filePath = request.getServletContext().getRealPath("/") + "upload";
					String mrchPic = "/upload"+ writeFile(file, filePath);
					dto.setMrchPic(mrchPic);
				}
			}
			this.commoditMrchService.saveOrUpdate(dto);
			res.setErrorMessage("修改商品商户成功");
			res.setResult(1);
		}catch(Exception e) {
			logger.error("修改商品商户异常：",e);
			res.setResult(2);
			res.setErrorMessage("修改商品商户失败");
		}
		return res;
	}
	
	@RequestMapping("/showCommoditMrch/{id}")
	@ResponseBody
	public DTOCommoditMrch showCommoditMrch(@PathVariable("id") String id) {
		//TODO
		return this.commoditMrchService.findById(id);
	}
	
	@RequestMapping("/disable/{id}")
	@ResponseBody
	public BaseAjaxResponse disable(@PathVariable("id") String id) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			boolean result = this.commoditMrchService.deleteById(id);
			if(result) {
				res.setResult(1);
				res.setErrorMessage("操作成功！");
			}else {
				res.setResult(2);
				res.setErrorMessage("操作失败！");
			}
		}catch(Exception e) {
			e.printStackTrace();
			logger.error("删除失败：",e);
			res.setResult(2);
			res.setErrorMessage("操作成功！");
		}
		return res;
	}
	
	@RequestMapping("/listCommodit/{mrchId}")
	public String listCommodit(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("criteria") DTOCommoditSearch criteria,@PathVariable("mrchId") String mrchId) {
		criteria.setTotalCount(-1);
		criteria.setMrchId(mrchId);
		DTOPagedList<DTOCommodit> pg = this.commoditMrchService.pageCommodit(criteria);
		modelMap.put("pg", pg);
		modelMap.put("dto", criteria);
		
		List<DataBean> beans = new ArrayList<DataBean>();
		beans.add(new DataBean("id", "id", "id", false, 150, 0));
		beans.get(beans.size() - 1).setHidden(true);
		beans.add(new DataBean("name", "name", "商户名称", false, 150, 0));
		beans.add(new DataBean("oldPrice", "oldPrice", "原价", false, 150, 0));
		beans.add(new DataBean("price", "price", "宝岛通价格", false, 150, 0));
		beans.add(new DataBean("picUrl", "picUrl", "商品图片", false, 150, 0));
		beans.add(new DataBean("desc", "desc", "商品描述", false, 150, 0));
		beans.add(new DataBean("createTime", "createTime", "创建时间", false, 150, 0));
		modelMap.put("beans", beans);
		modelMap.put("pageTitle", "商品商户信息");
	
		return "backend/ecard/list_commodit";
	}
	
	
	@RequestMapping(value="/addCommodit",method=RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse addCommodit(HttpServletRequest request,DTOCommodit dto) throws IOException {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			dto.setId(CommonUtils.getUUID());
			dto.setType("1");
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				MultipartFile file = multiRequest.getFile("addCommoditPicFile");
				if (null != file&&file.getSize()>0) {
					String filePath = request.getServletContext().getRealPath("/") + "upload";
					String picUrl = "/upload"+ writeFile(file, filePath);
					dto.setPicUrl(picUrl);
				}
			}
			this.commoditService.saveOrUpdate(dto);
			res.setErrorMessage("添加商品成功");
			res.setResult(1);
		}catch(Exception e) {
			logger.error("添加商品异常：",e);
			res.setResult(2);
			res.setErrorMessage("添加商品失败");
		}
		return res;
	}
	
	@RequestMapping(value="/editCommodit",method=RequestMethod.POST)
	@ResponseBody
	public BaseAjaxResponse editCommodit(HttpServletRequest request,DTOCommodit dto) throws IOException {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 获取multiRequest 中所有的文件名
				MultipartFile file = multiRequest.getFile("editCommoditPicFile");
				if (null != file&&file.getSize()>0) {
					String filePath = request.getServletContext().getRealPath("/") + "upload";
					String picUrl = "/upload"+ writeFile(file, filePath);
					dto.setPicUrl(picUrl);
				}
			}
			this.commoditService.saveOrUpdate(dto);
			res.setErrorMessage("修改商品成功");
			res.setResult(1);
		}catch(Exception e) {
			logger.error("修改商品异常：",e);
			res.setResult(2);
			res.setErrorMessage("修改商品失败");
		}
		return res;
	}
	
	@RequestMapping("/disableCommodit/{id}")
	@ResponseBody
	public BaseAjaxResponse disableCommodit(@PathVariable("id") String id) {
		BaseAjaxResponse res = new BaseAjaxResponse();
		try {
			boolean result = this.commoditService.deleteById(id);
			if(result) {
				res.setResult(1);
				res.setErrorMessage("操作成功！");
			}else {
				res.setResult(2);
				res.setErrorMessage("操作失败！");
			}
		}catch(Exception e) {
			e.printStackTrace();
			logger.error("删除失败：",e);
			res.setResult(2);
			res.setErrorMessage("操作成功！");
		}
		return res;
	}
	
	@RequestMapping("/showCommodit/{id}")
	@ResponseBody
	public DTOCommodit showCommodit(@PathVariable("id") String id) {
		//TODO
		return this.commoditService.findById(id);
	}
	
	public String writeFile(MultipartFile file, String uploadFile) throws IOException {
		InputStream in = null;
		FileOutputStream out = null;
		if (file != null) {
			Long fileSize = file.getSize();
			if (fileSize > 0 && fileSize < Long.parseLong(uploadFileSize)) {
				String path = "/";
				String fileRealName = file.getOriginalFilename();
				String md5Value = MD5Util.md5Hex(fileRealName.getBytes());
				String firstFour = md5Value.substring(0, 4);
				File firFile = new File(uploadFile, (path + firstFour));
				if (!firFile.exists() && !firFile.isDirectory()) {
					firFile.mkdirs();
				}
				String fileName = md5Value + fileRealName.substring(fileRealName.lastIndexOf("."));
				path = path + firstFour + "/" + fileName;
				File savePath = new File(uploadFile, path);
				if (!savePath.exists()) {// 当文件不存在时候才进行读写，否则跳出
					in = file.getInputStream();
					out = new FileOutputStream(savePath);
					byte[] b = new byte[1024];
					int len = -1;
					while ((len = in.read(b)) != -1) {
						out.write(b, 0, len);
					}
					out.flush();
				}
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
				return path;
			}
		}
		return null;
	}
}
